package com.workflowengine;

import com.workflowengine.config.WorkFlowContent;
import com.workflowengine.config.WorkFlowStatus;
import com.workflowengine.event.support.WorkFlowEventPublisher;
import com.workflowengine.workflowbase.AbstractWorkFlowCommand;
import com.workflowengine.workflowbase.bizCommand.BusinessCommand;
import com.workflowengine.workflowbase.bizCommand.StartCommand;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Package: com.workflowengine
 * @ClassName: WorkFlowService
 * @Author: h2cloud
 * @CreateTime: 2024/7/15 11:35 下午
 * @Description:
 */
@Service
@Log4j2
public class WorkFlowService {

	@Autowired
	private WorkFlowEventPublisher workFlowEventPublisher;

	// 根据流程类型和节点类型获取对应的 command
	public AbstractWorkFlowCommand getCommand() {
		StartCommand command = new StartCommand();
		return command;
	}

	public AbstractWorkFlowCommand getBusinessCommand() {
		BusinessCommand command = new BusinessCommand();
		return command;
	}

	public void startWorkFlow(WorkFlowContent content) {
		AbstractWorkFlowCommand command = getCommand();
		log.info("发起工作流");
		if (command.needCreateRecord(content)) {
			log.info("创建节点记录");
		}
		if (command.needCreateTodo(content)) {
			log.info("创建代办");
		}
		content.setStatus(WorkFlowStatus.WorkFlowStart);
		workFlowEventPublisher.publishEvent(content);
		content.setStatus(WorkFlowStatus.NodeStart);
		workFlowEventPublisher.publishEvent(content);
	}

	public void executeWorkFlow(WorkFlowContent content) {
		log.info("1、执行工作流；2、驱动流程引擎");

		// 当前节点
		AbstractWorkFlowCommand command = getCommand();
		log.info("执行当前节点业务逻辑");
		command.run(content);

		content.setStatus(WorkFlowStatus.NodeEnd);
		workFlowEventPublisher.publishEvent(content);

		// 下一节点
		content.setStatus(WorkFlowStatus.NodeStart);
		workFlowEventPublisher.publishEvent(content);
		if (command.needCreateRecord(content)) {
			log.info("创建下一节点记录");
		}
		if (command.needCreateTodo(content)) {
			log.info("创建下一节点代办");
		}
	}

}
